package com.example.understandvideo.tool;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ExcelTool {

    public static void main(String[] args) {
        String sourceFilePath = "table.json";
        String jsonFilePath = "target.json";
        String excelFilePath = "output.xlsx";
        Random random = new Random();
        int min = 8;
        int max = 20;


        try {
            // 读取 JSON 文件
            List<String> sourcedLines = readAndCleanJson(sourceFilePath);
            List<String> cleanedLines = new ArrayList<>();
            for (String line : sourcedLines) {
                String target = "" + (random.nextInt(max - min + 1) + min);
                cleanedLines.add(target);
            }
            // 将数据写入 Excel 文件
            writeExcel(cleanedLines, excelFilePath);

            System.out.println("Excel 文件已生成: " + excelFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String removeEndBiao(String str) {
        if (str != null && !str.isEmpty() && str.endsWith("表")) {
            return str.substring(0, str.length() - 1);
        }
        return str;
    }

    public static List<String> readAndCleanJson(String filePath) throws IOException {
        List<String> cleanedLines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
//                String cleanedValue = line.replaceAll("[0-9.,]", "");
                String cleanedValue = cleanPrefix(line);
                cleanedLines.add(cleanedValue);
            }
        }

        return cleanedLines;
    }

    private static String cleanPrefix(String input) {
        // 定义前缀模式
        //String prefixPattern = "^\\d+\\.\\s*ai数据处理-数据规整功能点-冗余数据剔除-";
        String prefixPattern = "- 媒体输出处理-多协议视频流接入-多协议并发输出-";

        // 使用正则表达式去除前缀
        return input.replaceAll(prefixPattern, "");
    }

    private static void writeExcel(List<String> data, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");

        int rowNum = 0;
        for (String line : data) {
            Row row = sheet.createRow(rowNum++);
            Cell cell = row.createCell(0);
            cell.setCellValue(line);
        }

        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }

        workbook.close();
    }
}
